package com.hk.Mgr.web.controller.app;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.Constant;
import com.hk.commons.LongId;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Activity;
import com.hk.commons.entity.FinancialLog;
import com.hk.commons.vo.ActivityReq;
import com.hk.commons.vo.ActivityRes;
import com.hk.commons.vo.JsonResult;
import com.hk.service.IFinancialLog;
import com.hk.service.kyc.IActivity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

@Controller
@RequestMapping(value = BaseCtrl.App + "/activityCtrl")
public class AppActivityCtrl extends BaseCtrl {

    @Autowired
    private IActivity activityService;

    @Autowired
    private IFinancialLog financialLogService;

    @Value("${activity.baseUrl}")
    private String baseUrl;

    private RestTemplate template = new RestTemplate();

    private Boolean switchToActivityCenter = true;

    /**
     * 获得所有订单信息, 旧接口，无需传channel
     *
     * @return
     * @author jeff
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBase<List<ActivityRes>> list() {
        ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();
        int channel = 1;

        if (switchToActivityCenter) {
            ActivityReq req = defaultActivityReq(channel);

            String url = baseUrl + "/api/activity/adapter/getAllList";

            return remoteCall(req, resp, url);
        }

        //old code
        List<ActivityRes> actReslist = activityService.getResByChannel(channel);
        resp.setResult(actReslist);
        resp.setSize(actReslist.size());
        return resp;
    }


    /**
     * 分发布渠道获取活动信息
     *
     * @param channel
     * @return
     */
    @RequestMapping(value = "/list01", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBase<List<ActivityRes>> list01(@RequestParam Integer channel) {
        ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();

        if (channel == null) {
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        if (switchToActivityCenter) {
            ActivityReq req = defaultActivityReq(channel);

            String url = baseUrl + "/api/activity/adapter/getAllList";

            return remoteCall(req, resp, url);
        }

        //old code
        List<ActivityRes> actReslist = activityService.getResByChannel(channel);
        resp.setSize(actReslist.size());
        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }


    /**
     * 新的获取活动内容的接口
     * 获得所有活动信息
     *
     * @return
     * @author jeff
     */
    @RequestMapping(value = "/getAll", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<List<ActivityRes>> getAll(@RequestBody ActivityReq req) {
        ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();

        if (req == null || req.getChannel() == null || req.getCurPage() == null || req.getPageSize() == null) {
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        Long userId = req.getUserId();

        if (userId != null) {
            FinancialLog financialLog = new FinancialLog();
            financialLog.setId(LongId.get());
            financialLog.setUserId(userId);
            financialLog.setCreated(Timestamp.valueOf(LocalDateTime.now()).getTime());
            financialLog.setChannel(req.getChannel());

            this.financialLogService.add(financialLog);
        }

        // support old version iOS app
        if (req.getCurPage() == 1)
            req.setCurPage(0);

        if (switchToActivityCenter) {
            String url = baseUrl + "/api/activity/adapter/getAllList";

            return remoteCall(req, resp, url);
        }

        return getOldwayAllListResult(req, resp, userId);
    }


    /**
     * 新的活动列表
     * 获得Bananer中的活动信息
     *
     * @return
     * @author jeff
     */
    @RequestMapping(value = "/getBananerActList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<List<ActivityRes>> getBananerActList(@RequestBody ActivityReq req) {
        ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();

        if (req == null || req.getChannel() == null || req.getCurPage() == null || req.getPageSize() == null) {
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        if (switchToActivityCenter) {
            String url = baseUrl + "/api/activity/adapter/getBannerActList";

            return remoteCall(req, resp, url);
        }

        return getOldwayBannerResult(req, resp);
    }


    /**
     * 新的Bananer的活动列表
     * 获得活动中心的活动信息
     *
     * @return
     * @author jeff
     */
    @RequestMapping(value = "/getActCenterList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<List<ActivityRes>> getActCenterList(@RequestBody ActivityReq req) {
        ResponseBase<List<ActivityRes>> resp = new ResponseBase<>();

        if (req == null || req.getChannel() == null || req.getCurPage() == null || req.getPageSize() == null) {
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        if (switchToActivityCenter) {
            String url = baseUrl + "/api/activity/adapter/getActCenterList";

            return remoteCall(req, resp, url);
        }

        return getOldwayCenterResult(req, resp);
    }


    /**
     * 改变活动的状态
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/read", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<Boolean> read(@RequestBody ActivityReq req) {
        ResponseBase<Boolean> resp = new ResponseBase<>();

        if (req == null || req.getUserId() == null || req.getId() == null) {
            resp.setResult(false);
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        Long userId = req.getUserId();
        Integer id = req.getId();
        activityService.read(id, userId);
        resp.setResult(true);
        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }

    /**
     * 改变活动的状态
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/readAll", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<Boolean> readAll(@RequestBody ActivityReq req) {
        ResponseBase<Boolean> resp = new ResponseBase<>();
        if (req == null || req.getUserId() == null || req.getChannel() == null) {
            resp.setResult(false);
            resp.setResultCode(StatusCode.PARAM_ERROR.key());
            resp.setMsg("参数错误！");
            return resp;
        }

        Integer channel = 1;
        if (StringHelper.isNotEmpty(req.getChannel())) {
            channel = Integer.valueOf(req.getChannel());
        }

        Long userId = req.getUserId();

        if (switchToActivityCenter) {
            String url = baseUrl + "/api/activity/adapter/getActCenterList";
            req.setCurPage(0);
            req.setPageSize(9999);
            JsonResult result = template.postForObject(url, req, JsonResult.class);
            List<LinkedHashMap> activitylist = (List<LinkedHashMap>) result.result;
            activityService.readAllByActivityList(activitylist, userId);
        } else {
            activityService.readAll(channel, userId);
        }

        resp.setResult(true);
        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }

    private ActivityReq defaultActivityReq(int channel) {
        ActivityReq req = new ActivityReq();
        req.setChannel(String.valueOf(channel));
        req.setCurPage(0);
        req.setPageSize(20);
        return req;
    }

    private ResponseBase<List<ActivityRes>> remoteCall(@RequestBody ActivityReq req, ResponseBase<List<ActivityRes>> resp, String url) {
        JsonResult result = template.postForObject(url, req, JsonResult.class);

        resp.setResult((List<ActivityRes>) result.result);

        return resp;
    }

    private ResponseBase<List<ActivityRes>> getOldwayAllListResult(@RequestBody ActivityReq req, ResponseBase<List<ActivityRes>> resp, Long userId) {
        Integer channel = Integer.valueOf(req.getChannel());
        Integer curPage = req.getCurPage();
        Integer pageSize = req.getPageSize();
        List<ActivityRes> actReslist = new ArrayList<>();

        logger.info("app ActivityRes get all list ,channel={}, curPage={}, pageSize={}", channel, curPage, pageSize);
        //List<Activity> list = activityService.getActiveActivity(channel, curPage, pageSize);

        //获取总数目
        List<Activity> totalList = activityService.getAllByChannel(channel);

        Collections.sort(totalList);

        List<Activity> list = activityService.page(curPage, pageSize, totalList);

        if (list == null || list.size() == 0) {
            resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
            return resp;

        }
        for (Activity ag : list) {
            ActivityRes activityRes = activityService.getRes(ag);
            Boolean isRead = false;
            if (userId != null) {
                isRead = activityService.isRead(ag.getId(), userId);
                activityRes.setRead(isRead);
            }

            actReslist.add(activityRes);
            resp.setResult(actReslist);


        }
        resp.setResult(actReslist);
        if (totalList != null && totalList.size() > 0) {
            resp.setSize(totalList.size());
        } else {
            resp.setSize(0);
        }

        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }

    private ResponseBase<List<ActivityRes>> getOldwayCenterResult(@RequestBody ActivityReq req, ResponseBase<List<ActivityRes>> resp) {
        Long userId = req.getUserId();

        Integer channel = Integer.valueOf(req.getChannel());
        String location = Constant.ACTIVITY_LOCATION_CENTER;
        Integer curPage = req.getCurPage();
        Integer pageSize = req.getPageSize();
        List<ActivityRes> actReslist = new ArrayList<>();

        logger.info("app ActivityRes get all list ,channel={}, curPage={}, pageSize={}", channel, curPage, pageSize);

        //获取总数目
        List<Activity> totalList = activityService.getResByChannelAndLocation(channel, location, userId);

        Collections.sort(totalList);

        List<Activity> list = activityService.page(curPage, pageSize, totalList);

        if (list == null || list.size() == 0) {
            resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
            return resp;
        }

        for (Activity ag : list) {
            ActivityRes activityRes = activityService.getRes(ag, userId);
            actReslist.add(activityRes);
        }

        resp.setResult(actReslist);

        if (totalList != null && totalList.size() > 0) {
            resp.setSize(totalList.size());
        } else {
            resp.setSize(0);
        }

        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }

    private ResponseBase<List<ActivityRes>> getOldwayBannerResult(@RequestBody ActivityReq req, ResponseBase<List<ActivityRes>> resp) {
        Long userId = req.getUserId();

        Integer channel = Integer.valueOf(req.getChannel());
        String location = Constant.ACTIVITY_LOCATION_BANANER;
        Integer curPage = req.getCurPage();
        Integer pageSize = req.getPageSize();
        List<ActivityRes> actReslist = new ArrayList<>();

        logger.info("app ActivityRes get all list ,channel={}, curPage={}, pageSize={}", channel, curPage, pageSize);

        //获取总数目
        List<Activity> totalList = activityService.getResByChannelAndLocation(channel, location, userId);

        Collections.sort(totalList);

        List<Activity> list = activityService.page(curPage, pageSize, totalList);

        if (list == null || list.size() == 0) {
            resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
            return resp;
        }

        for (Activity ag : list) {
            ActivityRes activityRes = activityService.getRes(ag, userId);
            actReslist.add(activityRes);
        }

        resp.setResult(actReslist);

        if (totalList != null && totalList.size() > 0) {
            resp.setSize(totalList.size());
        } else {
            resp.setSize(0);
        }

        resp.setResultCode(StatusCode.SUCCESS.key());
        return resp;
    }

}
